package com.swak.netty_udp.unicast2;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 * UdpNettyPeer. 
 * 
 * @author 618lf
 */
public class UdpNettyClient {
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap bootstrap;
	Channel channel;
	InetSocketAddress address;

	public UdpNettyClient(int port) throws InterruptedException {
		bootstrap = new Bootstrap();
		bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
				.option(ChannelOption.SO_RCVBUF, 2048 * 1024).option(ChannelOption.SO_SNDBUF, 1024 * 1024)
				.handler(new ChannelInitializer<NioDatagramChannel>() {
					@Override
					protected void initChannel(NioDatagramChannel ch) {
						ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast(new UdpClientHandler());
					}
				});
		this.address = new InetSocketAddress("localhost", port);
		ChannelFuture f = bootstrap.connect(address).sync();
		this.channel = f.channel();
		System.out.println("已经连接诶服务器:" + f.channel());
	}

	public void sendMessage(InetSocketAddress address, String message) {
		ByteBuf byteBuf = Unpooled.copiedBuffer(message.getBytes(StandardCharsets.UTF_8));
		this.channel.writeAndFlush(new DatagramPacket(byteBuf, address));
	}

	public void close() throws InterruptedException {
		this.channel.close().await();
	}

	public static void main(String[] args) throws InterruptedException {
		UdpNettyClient client = new UdpNettyClient(8088);
		client.sendMessage(client.address, "hello");

		// 服务器不会收到数据
		Thread.sleep(10000);
		System.out.println("发送个其他的服务器：");
		InetSocketAddress address = new InetSocketAddress("localhost", 60000);
		client.sendMessage(address, "hello");
	}
}
